import React, { Component, PropTypes } from "react";
import { connect } from "react-redux";
import autobind from "autobind-decorator";
import { bindActionCreators } from "redux";
import AntdCityData from "@ali/antdcitydata";
import { createForm } from "rc-form";
import fetch from "../utils/fetch.js";
import { List } from "@ali/ding-ui";

import { getFileKey } from "../actions/steps/getFiles";
import { controlBack } from "../utils/native.js";

// components
import Icon from "./Icon/index.jsx";
import Upload from "./Upload/index.jsx";
import ImagePicker from "./ImagePicker/";
import Select from "../components/Select/index";
import SchoolChooser from "../components/SchoolChooser/index";
import AreaSelect from "../components/AreaSelect/index";
import TextForm from "../modules/preview/textForm";
import DatePicker from "../components/DatePicker/index";
import { departmentsPicker, alert } from "../utils/dingtalk.js";

// utils
import { showHint } from "../utils/form.js";
import { type, getImageByFileKey, getUrlParam } from "../utils/common.js";
import { get } from "../utils/db.js";
import { getUrlHashParam } from "../utils/urlParams";

const Item = List.Item;

// 移除无用的props
function removeInvalidProps(tag, props) {
  // hack: ignore the unused variable declaration with /*eslint-disable no-unused-vars */
  // ref:https://github.com/babel/babel-eslint/issues/95
  const { fieldType: _, visible: __, value: ___, ...rest } = props;
  if (tag === "input") {
    const { options: ____, ...a } = rest;
    return a;
  }
  return rest;
}

let mainDept;

function goTo(hash) {
  window.location.hash = hash;
}

let initialHasChildren = false; // 后端给的是否有子女
const MAX_DEPARTMENTS = 100;

function isIDCardField(filed) {
  return ["sys08-rearIDcard", "sys08-forntIDcard"].indexOf(filed) !== -1;
}

// 如果是HR的话url中会有userId
function isHR() {
  return !!getUrlHashParam("userId");
}

function isPreviewPage() {
  return window.location.hash.indexOf("preview") !== -1;
}

function getIDCards(fieldList) {
  if (!fieldList.length) return [];

  return fieldList
    .filter(q => isIDCardField(q.props.id))
    .filter(q => q.props.value) // 按理说不用过滤的，因为员工端身份证是必填的
    .map(q => ({
      url: getImageByFileKey(get("baseUrl"), q.props.value),
      key: q.props.value //需要根据key获取真实的url
    }));
}

// abject -> string
// 将后端地址信息，解析为人可以理解的信息
function getAddress({ province = 0, city = 0, district = 0, address = "" }) {
  let d = { label: "" };
  if (!province) return "";
  const citys = AntdCityData;
  const p = citys.filter(_p => _p.value === province)[0];
  if (!p) return "";
  const c = p.children.filter(_c => _c.value === city)[0];
  if (!c) return p.label;
  if (c.children) {
    d = c.children.filter(_d => _d.value === district)[0];
  }
  if (!d) return p.label + c.label;
  return p.label + c.label + d.label;
}

function getDeptsOptions(depts, deptIds) {
  if (!depts) return [];
  if (!deptIds) return [];

  return depts
    .split(",")
    .map((dept, idx) => ({ value: deptIds.split(",")[idx], label: dept }));
}

// 根据不同的item类型来渲染不同的ReactELement
function renderItemComponent(item, id, label, required) {
  let Component = (
    <item.component
      key={id}
      title={label}
      {...removeInvalidProps(
        item.props.fieldType === "TextField" && "input",
        item.props
      )}
      placeholder={item.props.placeholder || "请输入"}
    >
      <span className={`step-one-${required ? "required" : "optional"}`}>
        *
      </span>

      <span className="label-left">{label}</span>
    </item.component>
  );
  return Component;
}

//将store注入组件的props
const mapStateToProps = state => ({ stepTwo: state.STEPS_STEPTWO });
//将action与dispatch进行绑定并注入组件的props
const mapDispatchToProps = dispatch => ({
  //区分绑定到props的action与传递的props
  actions: bindActionCreators(
    {
      dispatch,
      getFileKey
    },
    dispatch
  )
});

@connect(mapStateToProps, mapDispatchToProps)
class ProduceComponent extends Component {
  static defaultProps = {
    onRendered: () => null
  };
  //propTypes 验证
  static propTypes = {
    title: PropTypes.string,
    setFieldsValue: PropTypes.func,
    actions: PropTypes.shape({
      dispatch: PropTypes.func.isRequired,
      getFileKey: PropTypes.func.isRequired
    }).isRequired,
    savePhoto: PropTypes.func,
    list: PropTypes.array,
    getFieldDecorator: PropTypes.func,
    onRendered: PropTypes.func,

    validator: PropTypes.func,
    getFieldsValue: PropTypes.func
  };
  constructor(props) {
    super(props);

    this.onImageChange = this.onImageChange.bind(this);
    this.handleFileChange = this.handleFileChange.bind(this);
    this.state = {
    }
  }
  /**
   * 
   * @param {*string} label  标签label
   * @param {*string} value  标签值
   */
  //脱敏
  getAsterisk(label, value) {
    if (!value) {
      return "-"
    };
    try {
      const t = this;
      const asteriskRows = ["银行卡号", "证件号码", "个人社保账号", "个人公积金账号"];
      const asteriskYears = ["出生日期","实际生日"];
      const stateAsterisk = this.state["stateAsterisk" + label];
      const isShow = this.state["isShow" + label] === undefined;
      let textDiv = value;
      let isAsterisk = false;
      if (label === '手机号') {
        textDiv = value.substring(0, 3) + "*****" + value.substring(8, 11)
        isAsterisk = true;
      }
      if (asteriskRows.indexOf(label) !== -1) {
        textDiv = "**********";
        isAsterisk = true;
      }
      if (asteriskYears.indexOf(label) !== -1){
        textDiv = "******";
        isAsterisk = true;
      }

      return <span>{isAsterisk ? (stateAsterisk || textDiv) : value}
        {
          isAsterisk && isShow ? <span className='steps-asterisk' onClick={() => {
            const obj = {};
            obj["stateAsterisk" + label] = value;
            obj["isShow" + label] = false;
            t.setState(obj)
          }}>显示</span> : ""
        }
      </span>;
    } catch (error) {
      return value;
    }

  }
  /**
         * 调用钉钉手机版部门组件
         */
  @autobind
  handleDept() {
    const corpId = getUrlParam("corpId");

    // const corpId = get("corpId");
    //  const depts = this.props.getFieldsValue().depts;
    const deptIds = this.props.getFieldsValue().deptIds.split(",") || [];

    // const pickedDepartments = depts.split(",").map((dept, idx) => ({
    //   deptName: dept,
    //   deptId: deptIds[idx]
    // }));
    departmentsPicker({
      multiple: true, // 多选
      pickedDepartments: deptIds, // 已选部门
      maxDepartments: MAX_DEPARTMENTS, // 最大部门数
      corpId,
      cb: result => {
        const depts = [];
        const { departments } = result;
        departments.sort((a, b) => a.id - b.id);
        departments.forEach(val => {
          depts.push({ deptId: val.id, deptName: val.name });
        });

        //
        const deptIds = depts.map(dept => dept.deptId).join(",");

        this.props.setFieldsValue({
          depts: depts.map(dept => dept.deptName).join(",")
        });
        this.props.setFieldsValue({
          deptIds
        });

        // 没有主部门，则更新
        if (
          !this.props.getFieldsValue().mainDept ||
          deptIds.split(",").indexOf(this.props.getFieldsValue().mainDept) ===
            -1
        ) {
          this.props.setFieldsValue({ mainDept: depts[0].deptId });
        }
      },
      errCb: err => alert({ title: "出错了", message: JSON.stringify(err) })
    });
  }
  // 移除相册
  onImageChange({ props, isSystem, groupId }) {
    if (isSystem) {
      this.props.savePhoto({
        type: props.id,
        url: ""
      });
    } else {
      const item = {
        customFields: {}
      };
      item.customFields[groupId] = [
        {
          fieldCode: props.id,
          fieldType: "DDPhotoField",
          value: ""
        }
      ];
      this.props.savePhoto(item);
    }
  }
  componentWillMount = () => {
    if (this.props.list.length) {
      this.props.onRendered();
    }
  };

  handleFileChange({ props, isSystem, groupId }, file) {
    if (!file) return;

    // 上传文件
    this.props.actions.getFileKey(file.formData).then(res => {
      if (res.result) {
        // 获取fileKey成功，则保存fileKey

        if (isSystem) {
          this.props.savePhoto({
            type: props.id,
            url: res.result
          });
        } else {
          const item = {
            customFields: {}
          };
          item.customFields[groupId] = [
            {
              fieldCode: props.id,
              fieldType: "DDPhotoField",
              value: res.result
            }
          ];
          this.props.savePhoto(item);
        }

        const { setFieldsValue, getFieldsValue } = this.props;
        const __photo__ = getFieldsValue().__photo__;
        setFieldsValue({
          __photo__: { ...__photo__, ...{ [props.id]: file.url } }
        });
      }
    });
  }
  stub() {
    return () => () => null;
  }

  getLabel(options, value) {
    if (!value) return "";
    if (!options) return value;

    const match = options.filter(q => q.value === value)[0];
    if (!match) return "";
    return match.label;
  }
  openLink(hash) {
    dd.biz.util.openLink({
      url: `${window.location.origin}${window.location.pathname}#${hash}`,
      onFail: function(err) {
        console.log(err); // eslint-disable-line
      }
    });
  }
  @autobind
  isUploaded() {
    return this.props.certUploaded;
  }
  @autobind
  identify() {
    if (!this.isUploaded()) {
      goTo("identify");
    }
  }
  @autobind
  zoomIDCard(index, source) {
    controlBack(() => this._imagePicker.setState({ show: false }));
    this._imagePicker.setState({
      show: true,
      fs: source,
      index
    });
  }
  /**
   * 
   * @param {*Array} keys 一组图片数组
   * @param {*Integer} index 下标
   */
  previewPhotoSecret(keys, index) {
    fetch(`/hrmregister/mobile/emp/getAccessURLByFileKeys`, {
      body: keys,
      meta: {
        dipId: "",
        silence: true
      }
    }).then(res => {
      if (res && res.success) {
        dd.biz.util.previewImage({
          urls: res.result,
          current: res.result[index || 0]
        });
      }
    });
  }

  render() {
    const getFieldDecorator = this.props.getFieldDecorator || this.stub;

    const getFieldsValue = this.props.getFieldsValue || this.stub;

    const { validator,requireIDCard } = this.props;
    // 有无子女特殊逻辑处理
    if (!initialHasChildren) {
      initialHasChildren = this.props.list.filter(
        item => item.id === "sys07-haveChild"
      )[0];
      initialHasChildren = initialHasChildren && initialHasChildren.value;
    }
    const currentHasChildren = getFieldsValue()["sys07-haveChild"];

    const hasChild = currentHasChildren || initialHasChildren;
    // console.info(currentHasChildren, initialHasChildren);

    let t = this;

    return (
      <div className="step-two-list preview-profile">
        {this.props.title && (
          <div className="profile-title">{this.props.title}</div>
        )}

        {this.props.list.map((item, index) => {
          const props = item.props;
          const { id, label, required, value, fieldType } = props;
          //选择控件、日期控件 值为空的情况下，增加class
          const selectClassName =
            (props.fieldType === "DDSelectField" ||
              props.fieldType === "DatePicker" ||
              props.fieldType === "DDDateField") &&
            (props.value === "" || props.value === undefined)
              ? "profile-item-noSelect"
              : "";
          // 有无子女特殊逻辑处理
          const hide =
            (hasChild === false || hasChild === "0" || hasChild === "") &&
            [
              "sys07-childSex",
              "sys07-childName",
              "sys07-childBirthDate"
            ].indexOf(id) !== -1;

          if (id === "deptIds") {
            return (
              <div>
                {getFieldDecorator("deptIds", {
                  initialValue: value
                })(<div />)}
              </div>
            );
          }

          if (id === "mainDept" && !isPreviewPage()) {
            mainDept = value;
            return null;
          }

          // hr 编辑员工信息特殊逻辑（没几个不特殊逻辑了）
          if (!isPreviewPage() && isHR()) {
            if (id === "手机号" || id === "姓名") {
              return (
                <div className="profile-item hr-readonly">
                  <span className="profile-item-label">{label}</span>
                  <span className="profile-item-value">{value}</span>
                  <span className="profile-item-tips">{label}不可编辑</span>
                </div>
              );
            }
          }

          if (hide) return null;

          // 不可见直接删除
          if (!props.visible) return null;
          // 地址特殊逻辑
          if (id === "sys02-homeProvince" || id === "sys02-province") {
            if (!props.editable && !isPreviewPage())
              return (
                <div key={id}>
                  <TextForm
                    fieldName={label}
                    fieldValue={getAddress(
                      type(value) === "string" && value
                        ? JSON.parse(value)
                        : value || {}
                    )}
                  />
                  <div className="com-area-readonly">
                    {
                      (type(value) === "string" && value
                        ? JSON.parse(value)
                        : value || {}).address
                    }
                  </div>
                </div>
              );

            return (
              <div
                key={id}
                id={id}
                className={`profile-item ${!props.value
                  ? "profile-item-noSelect"
                  : ""}`}
              >
                {getFieldDecorator(id, {
                  initialValue: value,
                  rules: [
                    {
                      label,
                      id,
                      validator,
                      required,
                      cache: getFieldsValue(),
                      max: (props.max || 50) + 70 // why 70 ? see readme
                    }
                  ]
                })(
                  <AreaSelect
                    initialValue={value}
                    required={required}
                    getLocation={id === "sys02-homeProvince" ? true : false}
                    text={
                      <span>
                        <span
                          className={`step-one-${required
                            ? "required"
                            : "optional"}`}
                        >
                          *
                        </span>
                        {label}
                      </span>
                    }
                    label={label}
                    data={AntdCityData}
                  />
                )}
                {showHint(item)}
              </div>
            );
          }
          // HR端 身份证特殊逻辑
          if (!props.editable && fieldType === "DDPhotoField") {
            if (id === "sys08-forntIDcard") {
              let fileImages = getIDCards(this.props.list) || [];
              let keys = fileImages.map(item => {
                return item.key;
              });
              return (
                <div
                  key={id}
                  className="preview-upload-layout no-close preview-profile"
                >
                  <div className="preview-profile-group preview-image">
                    <div className="preview-profile-field">
                      <span className="preview-profile-field-span">身份证</span>
                    </div>
                    <div className="preview-photo-secret">
                      {//显示身份证图片
                      fileImages.map((fileImage, index) => {
                        return (
                          <img
                            key={index}
                            onClick={() => t.previewPhotoSecret(keys, index)}
                            src={fileImage.url}
                          />
                        );
                      })}
                    </div>
                  </div>
                </div>
              );
            } else if (id === "sys08-rearIDcard") {
              return null;
            }
            return (
              <div
                className={`${value &&
                  "preview-image"} preview-profile-group no-close`}
                key={id}
              >
                <span className="preview-profile-field">
                  <span className="preview-profile-field-span">{label}</span>
                </span>
                <span className="preview-profile-value">
                  {!value && <span>-</span>}
                </span>
                <div className="preview-photo-secret">
                  <img
                    key={index}
                    onClick={() => t.previewPhotoSecret([value])}
                    src={getImageByFileKey(get("baseUrl"), value)}
                  />
                </div>
              </div>
            );
          }
          // 除了图片之外的只读字段
          if (
            !props.editable && // 不可编辑不显示必填的标志，即使他是必填的
            isPreviewPage()
          )
            return (
              <div key={id}>
                {id === "sys03-graduateSchool" ? (
                  <SchoolChooser readonly={!props.editable} value={value}>
                    <span
                      className={`step-one-${required
                        ? "required"
                        : "optional"}`}
                    >
                      *
                    </span>
                  </SchoolChooser>
                ) : (
                  <div className="preview-profile-group">
                    <span className="preview-profile-field">
                      <span className="preview-profile-field-span">
                        {label}
                      </span>
                    </span>
                    <span
                      className={`preview-profile-value ${label.length > 5 &&
                        "newline"}`}
                    >
                      {fieldType === "DDSelectField" ? (
                        this.getLabel(props.options, value) || "-"
                      ) : (
                            this.getAsterisk(label, value)
                      )}
                    </span>
                  </div>
                )}
              </div>
            );
          // 员工端的日期字段
          if (item.component === DatePicker) {
            return (
              <div key={id} className={`profile-item ${selectClassName}`}>
                {getFieldDecorator(id, {
                  initialValue: value,
                  rules: [
                    { required, validator, label, type: "datePicker", id }
                  ]
                })(
                  <DatePicker
                    label={label}
                    required={required}
                    placeholder={item.props.placeholder}
                  />
                )}
                {showHint(item)}
              </div>
            );
          } else if (item.component === "DDPhotoField") {
            // 员工端的身份证特殊逻辑
            if (id === "sys08-forntIDcard") {
              if (isHR()) return null;
              return (
                <div
                  key={id}
                  name="id-card"
                  className="profile-item"
                  onClick={this.identify}
                >
                  <Item>
                    <span
                      className={`step-one-${requireIDCard
                        ? "required"
                        : "optional"}`}
                    >
                      *
                    </span>

                    <span className="title">身份证上传</span>
                    <a onClick={this.identify}>
                      {this.isUploaded() ? (
                        <span className="step-one-upload">已上传</span>
                      ) : (
                        <Icon type="right" />
                      )}
                    </a>
                  </Item>
                  {showHint()}
                </div>
              );
            } else if (id === "sys08-rearIDcard") {
              return null;
            }
            // 员工端图片字段
            return (
              <div key={props.id} className="employ-photo profile-item">
                <Item>
                  <span className="title">
                    {
                      <span
                        className={`step-one-${required
                          ? "required"
                          : "optional"}`}
                      >
                        *
                      </span>
                    }
                    {props.label}
                  </span>
                  <a>
                    <Upload
                      onFileChange={this.handleFileChange.bind(this, item)}
                    >
                      {/* <Icon type="camera-o" /> */}
                      <img
                        className="camera"
                        src="https://img.alicdn.com/tfs/TB11rgacjihSKJjy0FeXXbJtpXa-54-48.png"
                        alt=""
                      />
                    </Upload>
                  </a>

                  {this.props.getFieldDecorator(`__photo__.[${props.id}]`, {
                    initialValue: getImageByFileKey(get("baseUrl"), value),
                    rules: [
                      {
                        required: required,
                        label,
                        validator,
                        id
                      }
                    ]
                  })(
                    <ImagePicker
                      onImageChange={() => this.onImageChange(item)}
                      selectable={false}
                    />
                  )}
                </Item>
                {showHint(item)}
              </div>
            );
          }

          // 员工端其他字段
          if (id === "部门" && isHR()) {
            return (
              <div>
                <div className="profile-item">
                  {getFieldDecorator("depts", {
                    initialValue: value,
                    rules: [
                      {
                        label,
                        validator,
                        required,
                        cache: getFieldsValue(),
                        id
                      }
                    ]
                  })(
                    <item.component
                      editable={false}
                      placeholder="请选择部门"
                      onClick={this.handleDept}
                      id="dept-input"
                    >
                      <span
                        className={`step-one-${required
                          ? "required"
                          : "optional"}`}
                      >
                        *
                      </span>
                      部门
                    </item.component>
                  )}
                  <div className="profile-item">
                    {(getFieldsValue().depts || "").split(",").length > 1 &&
                      getFieldsValue().deptIds &&
                      getFieldDecorator("mainDept", {
                        initialValue:
                          mainDept ||
                          (getFieldsValue().deptIds || "").split(",")[0],
                        rules: [
                          {
                            label,
                            validator,
                            required,
                            cache: getFieldsValue(),
                            id
                          }
                        ]
                      })(
                        <Select
                          options={getDeptsOptions(
                            getFieldsValue().depts,
                            getFieldsValue().deptIds
                          )}
                        >
                          <span
                            className={`step-one-${required
                              ? "required"
                              : "optional"}`}
                          >
                            *
                          </span>
                          主部门
                        </Select>
                      )}
                  </div>
                </div>
                <div />
              </div>
            );
          }
          return (
            <div key={id} className={`profile-item ${selectClassName}`}>
              {getFieldDecorator(id, {
                initialValue: value || "",
                rules: [
                  {
                    max: props.max || 50,
                    label,
                    validator,
                    required,
                    cache: getFieldsValue(),
                    id
                  }
                ]
              })(
                id === "sys03-graduateSchool" ? (
                  <SchoolChooser readonly={!props.editable}>
                    <span
                      className={`step-one-${required
                        ? "required"
                        : "optional"}`}
                    >
                      *
                    </span>
                  </SchoolChooser>
                ) : (
                  <item.component
                    key={id}
                    title={label}
                    {...removeInvalidProps(
                      item.props.fieldType === "TextField" && "input",
                      item.props
                    )}
                    placeholder={
                      item.props.placeholder ||
                      item.props.fieldType === "DDSelectField" ? (
                        "请选择"
                      ) : (
                        "请输入"
                      )
                    }
                  >
                    <span
                      className={`haha step-one-${required
                        ? "required"
                        : "optional"}`}
                    >
                      *
                    </span>
                    <span className="label-left">{label}</span>
                  </item.component>
                )
              )}
              {showHint(item)}
            </div>
          );
        })}
      </div>
    );
  }
}
export default createForm()(ProduceComponent);
